package com.cbtx.networklib.interceptor

import com.cbtx.networklib.util.SignUtil
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/29 6:10 PM
 * desc   : header拦截器，用于添加请求头，所添加内容由调用者在创建该拦截器时自行传入
 */
class HeaderInterceptor constructor(var headers: Map<String, String?>) : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var original = chain.request()
        val requestBuilder = original.newBuilder()
        if (headers.isNotEmpty()) {
            for (key in headers.keys) {
                headers[key]?.let { requestBuilder.addHeader(key, it) }
            }
        }
        // 此处header是为应用独特添加
        requestBuilder.addHeader("sign", SignUtil.getSign(original, System.currentTimeMillis()))
        original = requestBuilder.build()
        return chain.proceed(original)
    }
}